package com.sxs.thymeleaf_study.controller;

import com.sxs.thymeleaf_study.vo.ResultVo;
import lombok.val;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${web.upload-path}")    //读取到上传图片位置
    private String uploadPath; //路径

    @PostMapping()
    public ResultVo upload(MultipartFile file){

        if(!file.isEmpty()){
            //上传路径      uplkoad
            String originalFilename = file.getOriginalFilename();
            //fileSuffix 文件后缀名
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            if(file.getSize()>500*1024){
                throw new RuntimeException("文件够大");
            }else if(fileSuffix.equalsIgnoreCase("jpg") || fileSuffix.equalsIgnoreCase("jpeg")
                    || fileSuffix.equalsIgnoreCase("png") || fileSuffix.equalsIgnoreCase("gif")){
                File savePath = new File(uploadPath);
                
                //正常上传
                String fileName = UUID.randomUUID().toString().replace("-","");
                File saveFile = new File(uploadPath+fileName+fileSuffix);

                try {
                    file.transferTo(saveFile);
                } catch (IOException e) {
                    throw new RuntimeException("文件上传异常了");
                }
            }else {
                throw new RuntimeException("必须是图片");
            }
        }else {

        }
        return null;
    }
}
